package com.tannuo.dolphinnotedemo.sdk.device.protocol;

import com.tannuo.dolphinnotedemo.sdk.util.DataUtil;

import java.nio.ByteBuffer;

/**
 * Created by Nick on 2016/8/8.
 * mess
 */
public abstract class MessageBase implements IMessage {

    // 消息内容
    private byte[] id;
    private byte[] data;
    private byte[] feature;

    @Override
    public void setId(byte[] newValue) {
        this.id = newValue;
    }

    @Override
    public byte[] getId() {
        return id;
    }

    @Override
    public void setData(byte[] newValue) {
        data = newValue;
    }

    @Override
    public byte[] getData() {
        return data;
    }

    @Override
    public byte[] getFeature() {
        return feature;
    }

    @Override
    public void setFeature(byte[] newValue) {
        feature = newValue;
    }

    @Override
    public int getFeatureInt() {
        return 0xdd;
    }

    @Override
    public void setFeature(int value) {

    }

    public int getTotalLen() {
        return ProtocolCode.LENGTH_HEADER + ProtocolCode.LENGTH_FEATURE + ProtocolCode.LENGTH_ID +
                ProtocolCode.LENGTH_DATA_SIZE + getDataLen() + ProtocolCode.LENGTH_CHECKSUM + ProtocolCode.LENGTH_END;
    }

    public int getDataLen() {
        return data == null ? 0 : data.length;
    }

    private byte checkSum() {
//        throw new NotImplementException();
        return 1;
    }

    @Override
    public byte[] getBytes() {
        ByteBuffer buffer = ByteBuffer.allocate(getTotalLen());
        buffer.put(ProtocolCode.MESSAGE_HEADER, 0, ProtocolCode.LENGTH_HEADER);
        buffer.put(this.getFeature(), 0, ProtocolCode.LENGTH_FEATURE);
        buffer.put(this.getId(), 0, ProtocolCode.LENGTH_ID);
        buffer.put(DataUtil.int2byteLen2Low(this.getDataLen()), 0, ProtocolCode.LENGTH_DATA_SIZE);
        if (this.getDataLen() > 0) {
            byte[] content = this.getData();
            buffer.put(content, 0, content.length);
        }
//        byte checksum = checkSum();
//        buffer.put(checksum);
        buffer.put(ProtocolCode.MESSAGE_END, 0, ProtocolCode.LENGTH_END);
        buffer.put(ProtocolCode.MESSAGE_END, 0, ProtocolCode.LENGTH_END);
        byte[] data = buffer.array();
        return data;
    }


}
